<?php

namespace App\Http\Controllers\AppApi\Member;

use App\admin\Service\OA;
use App\Jobs\Fun;
use App\Models\Admin\YzmModel;
use App\Models\AreaModel;
use App\Models\User\UserModel;
use App\Services\Admin\UserService;
use App\Services\Jiguang\JMessageApi;
use App\Utilities\Sms;
use App\Utilities\Upload;
use App\Utilities\Utility;
use Illuminate\Http\Request;
use Hash;
use Cookie;
use JMessage\JMessage;

class LoginController extends BaseController
{
    /**
     * 登陆注册
     * 制作者：九哥
     */

    protected $userService;

    public function __construct()
    {
        parent::__construct();

        $this->userService = new UserService();
    }

    /**
     * 登陆
     */
    public function doLogin(Request $request)
    {
       // Cookie::queue('p_token','sssssssssf', 10000+time());


        $phone = $request->phone;
        $pwd = $request->pwd;
        if ($request->app_access != $this->app_access) {
            return $this->toJson(-1);
        }
        if (!preg_match('/^1[34578]\d{9}$/', $phone)) {
            return $this->toJson(-8);
        }
        $model = $this->userService->getOneByMobile($phone);
        if (!$model) {
            return $this->toJson(-9);
        }
        if (!(Hash::check($pwd, $model->password))) {
            return $this->toJson(-10);
        }
        $userModel=new UserModel;
        $token=$userModel->accessSet($model->id);
       // $token = $this->accessSet($model->id);
       /* $cate = $this->userService
            ->getUserType($model->id, $model->type);*/
        $resArr = array(
            'token' => $token,
            'is_company'=>$model->is_company,
            'is_factory'=>$model->is_factory,
            'is_yingpin'=>$model->is_yingpin,
            'head'=>Fun::pImg($model->head),
            'name'=>$model->name,
            'id'=>$model->id,
        //    'type' => $model->type,
        //    'cate' => $cate,
        );


        ///  Cookie::queue('p_token','sssssssssf', 24 * 3600 * 7);
        return response($this->toJson(0, $resArr))->cookie('token',$token, 60*24*7,null,null,false,false);
    }

    /**
     * 注册
     */
    public function doRegist(Request $request)
    {

        $phone = $request->phone;
        $pwd = $request->pwd;
        $yzm = $request->yzm;
        if ($request->app_access != $this->app_access) {
            return $this->toJson(-1);
        }
        if (!$phone || !$pwd || !$yzm) {
            return $this->toJson(-2);
        }

        if ($yzm != '1234') {
            //验证码校验
            $resYzm = $this->getYzm($phone);
            if (!$resYzm || $yzm !== $resYzm) {
                return $this->toJson(-7);
            }
        }
        if (!preg_match('/^1[345678]\d{9}$/', $phone)) {
            return $this->toJson(-8);
        }
        if (!preg_match('/^[0-9a-zA-Z_]{5,20}$/', $pwd)) {
            return $this->toJson(-12);
        }
        $model = $this->userService->getOneByMobile($phone);
        if ($model) {
            return $this->toJson(-4);
        }
        //保存信息
        $nameStr = '新用户';
        $pwdHash = Hash::make($pwd);
        $Jiguang_pass=md5($pwdHash.time());
        $jiguang_id=JMessageApi::getRandChar();
        $dataArr = array(
            'name' => $nameStr,
            'phone' => $phone,
            'password' => $pwdHash,
            'jiguang_id'=>$jiguang_id,
            'jiguang_pass' => $Jiguang_pass,

            'is_company'=>0,
            'is_factory'=>0,
            'is_yingpin'=>0,
            'head'=> Fun::pImg(UserModel::defaultHead)
        );

        $lastId = $this->userService->add($dataArr);

        //生成token
       /// $token = $this->accessSet($lastId);
        ///
        $userModel=new UserModel;
        $token=$userModel->accessSet($lastId);
        JMessageApi::register($jiguang_id,$Jiguang_pass);
        JMessageApi::upNameNick($jiguang_id,$nameStr);

        /** 'is_company'=>$model->is_company,
        'is_factory'=>$model->is_factory,
        'is_yingpin'=>$model->is_yingpin,
        'head'=>Fun::pImg($model->head),
        'name'=>$model->name,*/

        $resArr = array(
            'token' => $token,
            'is_company'=>0,
            'is_factory'=>0,
            'is_yingpin'=>0,
            'id'=>$lastId,
            'head'=> Fun::pImg(UserModel::defaultHead)
           // 'type' => 0,
         ///   'cate' => 0,
        );

        //记录用户须知
      //  $this->userService->setUserNotice($lastId);

        return response($this->toJson(0, $resArr))->cookie('token',$token, 60*24*7);
      //  return $this->toJson(0, $resArr);
    }

    /**
     * 发送验证码
     */
    public function sendYzm(Request $request)
    {
        //   return $this->toJson(0); //先屏蔽验证码
        $phone = $request->phone;
        if ($request->app_access != $this->app_access) {
            return $this->toJson(-1);
        }
        if (!preg_match('/^1[34578]\d{9}$/', $phone)) {
            return $this->toJson(-8);
        }
        $resYzm = $this->getYzm($phone);
        if ($resYzm) {
            return $this->toJson(-6, [], '刚刚已经发送给验证码');
        }
//        $code = Utility::getRandStr(rand(4,6),0);
        $code = Utility::getRandStr(4, 0);
        /// YzmModel::deleted();
        $dataArr = array(
            'phone' => $phone,
            'code' => $code,
            'created_at' => time(),
        );
        $lastId = YzmModel::insertGetId($dataArr);
        $sms = new Sms();
        $msg = "【美策】验证码{$code}，您正在进行美策平台的账号注册，有效时间30分钟身份验证，打死不要告诉别人哦！";
        /*
        $resSms = $sms->sendSMS($phone, $msg);
        $resSms = json_decode($resSms, true);
        if (empty($resSms) || !empty($resSms['errorMsg'])) {
            return $this->toJson(-11);
        }*/
        YzmModel::where('id', $lastId)->update(array('status' => 2));
        return $this->toJson(1, [], '万能验证码是:1234;临时关闭短信发送,短信内容是:' . $msg);


        return $this->toJson(0);
    }

    /**
     * 密码重置
     */
    public function setPwd(Request $request)
    {
        $phone = $request->phone;
        $pwd = $request->pwd;
        $yzm = $request->yzm;
        if ($request->app_access != $this->app_access) {
            return $this->toJson(-1);
        }
        if (!$phone || !$pwd || !$yzm) {
            OA::Json(1,'参数错误');
         //   return $this->toJson(-2);
        }
//        //验证码校验
       $resYzm = $this->getYzm($phone);
        if (!$resYzm) {
            OA::Json(1,'验证码过期了,请重新获取验证码');
        }
        if($resYzm!=$yzm){
            OA::Json(1,'验证码输入错误');
        }

        if (!preg_match('/^1[34578]\d{9}$/', $phone)) {
            return $this->toJson(-8);
        }
        if (!preg_match('/^[0-9a-zA-Z_]{5,20}$/', $pwd)) {
            return $this->toJson(-12);
        }
        $model = $this->userService->getOneByMobile($phone);
        if (!$model) {
            return $this->toJson(-9);
        }
        $this->userService->setPwdByMobile($phone, Hash::make($pwd));
        return $this->toJson(0);
    }

    /**
     * 设置主体身份
     */
    public function setIndentity(Request $request)
    {
        $token = $request->token;
        $introducer = $request->introducer;
        if ($request->app_access != $this->app_access) {
            return $this->toJson(-1);
        }
       /* if (!$token) {
            return $this->toJson(-2);
        }*/
        $uid = $this->accessGet($token);
        if (!$uid) {
            return $this->toJson(-13);
        }
        $user=UserModel::where(['id'=>$uid])->first();
        if(!$user){
            OA::Json(1,'参数错误');
        }
        if(!empty($user->introducer)){
            OA::Json(1,'介绍人已经设置过了');
        }
        $user->introducer=$introducer;
        if($user->save()){
            return $this->toJson(0);
        }else{
            OA::Json(1,'保存错误,可能是参数错误');
        }
        return $this->toJson(0);
    }

    /**
     * 获取生日的天
     */
    public function getBirthDay(Request $request)
    {
        if ($request->app_access != $this->app_access) {
            return $this->toJson(-1);
        }
        $month = $request->month;
        if ($month < 1 || $month > 12) {
            return $this->toJson(-2);
        }
        $dayStr = '';
        if ($month == 2) {
            for ($i = 1; $i <= 28; $i++) {
                if ($i < 10) {
                    $i = '0' . $i;
                }
                $dayStr .= '<option value="' . $i . '">' . $i . '</option>';
            }
        } else if (in_array($month, [1, 3, 5, 7, 8, 10, 12])) {
            for ($i = 1; $i <= 31; $i++) {
                if ($i < 10) {
                    $i = '0' . $i;
                }
                $dayStr .= '<option value="' . $i . '">' . $i . '</option>';
            }
        } else {
            for ($i = 1; $i <= 30; $i++) {
                if ($i < 10) {
                    $i = '0' . $i;
                }
                $dayStr .= '<option value="' . $i . '">' . $i . '</option>';
            }
        }
        return $this->toJson(0, $dayStr);
    }

    /**
     * 获取验证码
     */
    public function getYzm($phone)
    {
        ///  return true; //先取消验证码验证
//        $start = strtotime(date('Ymd').'000000');
//        $end = strtotime(date('Ymd').'235959');
        $model = YzmModel::where('phone', $phone)
            ->where('status', 2)
//            ->where('created_at','>',$start)
//            ->where('created_at','<=',$end)
            ->where('created_at', '>', time() -   30)
            ->first();
        return $model ? $model->code : '';
    }

    /**
     * 获取地区
     */
    public function getRegions(Request $request)
    {
        if ($request->app_access != $this->app_access) {
            return $this->toJson(-1);
        }
        $pid = $request->pid;
        $models = AreaModel::where('pid', $pid)->get();
        $dataArr = array();
        if (!count($models)) {
            return $this->toJson(-3);
        }
        foreach ($models as $k => $model) {
            $dataArr[$k]['id'] = $model->id;
            $dataArr[$k]['name'] = $model->name;
        }
        return $this->toJson(0, $dataArr);
    }

    /**
     * IOS用，判断H5
     */
    public function isH5ByIos(Request $request)
    {
        return $this->toJson(0, array('ios' => 1));
    }

    /**
     * 图片上传通用方法
     * /api/member/upload/img
     */
    public function setUploadImg(Request $request)
    {


        if ($request->app_access != $this->app_access) {
            return $this->toJson(-1);
        }
        /*
         * 临时关闭用户验证
         *
        $token = $request->token;
        if (!$token) {
            return $this->toJson(-2);
        }

        $uid = $this->accessGet($token);
        if (!$uid) {
            return $this->toJson(-13);
        }
        */
        if (!isset($request->img)) {
            return $this->toJson(-17);
        }
        $resImg = Upload::uploadImgByApi($request, 'img');

        if ($resImg['code'] != 0) {
            return $this->toJson(-23,[],$resImg['msg']);
        }
        $img = $resImg['filePath'];
        $dataArr = array(
            'uid' => OA::$user->getId(),
            'url' => $img,
            'created_at' => time(),
        );
        $this->userService->setImgTmp($dataArr);
        ///print_r($resImg);exit;
        return $this->toJson(0, array(
            'img' => Fun::pImg($img),
            'big' => Fun::pImg($resImg['big'])
        ));
    }

    /**
     * 用户须知
     */
    public function setUserNotice(Request $request)
    {
        if ($request->app_access != $this->app_access) {
            return $this->toJson(-1);
        }
        $token = $request->token;
      /*  if (!$token) {
            return $this->toJson(-2);
        }*/
        $uid = $this->accessGet($token);
        if (!$uid) {
            return $this->toJson(-13);
        }
        $this->userService->setUserNotice($uid);
        return $this->toJson(0);
    }
}